#!/usr/bin/env python
#! encoding: utf-8

import logging
import os
import re
import tempfile
from sys import version_info
import ConfigParser


python_major = tuple(version_info)[0]
logging.basicConfig(format='%(levelname)s:\t%(message)s', level=logging.DEBUG)

log = logging

def init_config_file(path):
    global portal_db_user 
    global portal_db_passwd 
    global portal_host 
    global portal_port 
    
    global gc_db_url 
    
    global zookeeper_host 
    global zookeeper_port 
    
    global redis_host 
    global redis_port 
    global redis_sentinel1_ip 
    global redis_sentinel1_port 
    global redis_sentinel2_ip 
    global redis_sentinel2_port 
    
    global portal_ftpHostIp 
    global portal_ftpPort 
    global portal_ftp_userName 
    global portal_ftp_password 
    
    global om_ftpHostIp 
    global om_ftpPort 
    global om_ftp_userName 
    global om_ftp_password 
    
    global cas_host 
    global cas_port 
    
    global om_host 
    global om_port 
    global om_db_user 
    global om_db_passwd 
    
    global wfm_host 
    global wfm_port 
    global wfm_db_user 
    global wfm_db_passwd 
    global wfm_db_user2 
    global wfm_db_passwd2 
    
    global am_host 
    global am_port 
    global am_db_user 
    global am_db_passwd 
    
    global weatherUrl 
    
    global bwp_db_user 
    global bwp_db_passwd 
    global bwp_host 
    global bwp_port 
    
    global mongodb_host 
    global mongodb_port 
    global mongodb_defaultDbName 
    global mongodb_user 
    global mongodb_passwd 
    cf = ConfigParser.ConfigParser()
    cf.read(path)
    portal_db_user = cf.get("PORTAL", "db_user")
    portal_db_passwd = cf.get("PORTAL", "db_pass")
    portal_host = cf.get("PORTAL", "host")
    portal_port = cf.get("PORTAL", "port")
    
    gc_db_url = cf.get("GCDB", "jdbc_url")
    
    zookeeper_host = cf.get("zookeeper", "host")
    zookeeper_port = cf.get("zookeeper", "port")
    
    redis_host = cf.get("redis", "host")
    redis_port = cf.get("redis", "port")
    redis_sentinel1_ip = cf.get("redis", "redis_sentinel1_ip")
    redis_sentinel1_port = cf.get("redis", "redis_sentinel1_port")
    redis_sentinel2_ip = cf.get("redis", "redis_sentinel2_ip")
    redis_sentinel2_port = cf.get("redis", "redis_sentinel2_port")
    
    portal_ftpHostIp = cf.get("ftp", "portal_host")
    portal_ftpPort = cf.get("ftp", "portal_port")
    portal_ftp_userName = cf.get("ftp", "portal_userName")
    portal_ftp_password = cf.get("ftp", "portal_password")
    
    om_ftpHostIp = cf.get("ftp", "om_host")
    om_ftpPort = cf.get("ftp", "om_port")
    om_ftp_userName = cf.get("ftp", "om_userName")
    om_ftp_password = cf.get("ftp", "om_password")
    
    cas_host = cf.get("cas", "host")
    cas_port = cf.get("cas", "port")
    
    om_host = cf.get("OM", "host")
    om_port = cf.get("OM", "port")
    om_db_user = cf.get("OM", "db_user")
    om_db_passwd = cf.get("OM", "db_pass")
    
    wfm_host = cf.get("WFM", "host")
    wfm_port = cf.get("WFM", "port")
    wfm_db_user = cf.get("WFM", "db_user")
    wfm_db_passwd = cf.get("WFM", "db_pass")
    wfm_db_user2 = cf.get("WFM", "db_user2")
    wfm_db_passwd2 = cf.get("WFM", "db_pass2")
    
    am_host = cf.get("AM", "host")
    am_port = cf.get("AM", "port")
    am_db_user = cf.get("AM", "db_user")
    am_db_passwd = cf.get("AM", "db_pass")
    
    weatherUrl = cf.get("weather", "url")
    
    bwp_db_user = cf.get("BWP", "db_user")
    bwp_db_passwd = cf.get("BWP", "db_pass")
    bwp_host = cf.get("BWP", "host")
    bwp_port = cf.get("BWP", "port")
    
    mongodb_host = cf.get("mongodb", "host")
    mongodb_port = cf.get("mongodb", "port")
    mongodb_defaultDbName = cf.get("mongodb", "defaultDbName")
    mongodb_user = cf.get("mongodb", "db_user")
    mongodb_passwd = cf.get("mongodb", "db_pass")
    
    
init_config_file('gc_config.ini')
def startswith_multi_keys(line, keys):
    pass

def replace(path,conf,is_check=False):


    with open(path,'r') as o_file:
        s_lines = o_file.readlines()

    check_l = []
    to_lines = []
    for line in s_lines:
        for c in conf:
            if c[0] in line:
                check_l.append([line, c[1]])
                line = c[1] if c[1].endswith('\n') else c[1] + '\n'
                
        to_lines.append(line)


    if not is_check:
        with open(path, 'w') as w_open:
            w_open.writelines(to_lines)
    else:
        s = '\n'.join('from--- [ {0} ] ---to--- [ {1} ]---'.format(b[0].strip(),b[1].strip()) for b in check_l)
        log.info('-'*30)
        log.info('we will modify file:%s '%path)
        log.info(s)
        log.info('-'*30)

    return


def rex_replace(path, conf, is_check=False):

    with open(path, "r") as o_file:
        log.debug('read file %s' %path)
        source_str = o_file.read()

    check_l = []
    check_not_match = []

    if not is_check:
        for c in conf:
            match = re.search(c[0], source_str)
            log.debug('regular expression is : %s'%c[0])
            if match:
                match_origin_str = match.group()
                match_repleaced_str = re.sub(match.group(1), c[1], match_origin_str)
                source_str = re.sub(match_origin_str, match_repleaced_str, source_str)
        # print(source_str)
        # exit()
        with open(path, "w") as w_open:
            w_open.write(source_str)
    else:
        for c in conf:
            
            match = re.search(c[0], source_str)
            log.debug('regular expression is : %s'%c[0])
            
            if match.groups():
                
                log.debug('match group : %s'%match.groups())
                
                match_origin_str = match.group()
                match_repleaced_str = re.sub(match.group(1), c[1], match_origin_str)
                #log.info('-------%s %s'%(match_origin_str,match_repleaced_str))
               
                check_l.append([match_origin_str, match_repleaced_str])
            else:
                check_not_match.append(c[0])

            # print(check_l)
            # exit()
        
        c_s = "\n".join(
            "\nfrom--- [ {0} ] ---to--- [ {1} ]---\n".format(b[0].strip(), b[1].strip())
            for b in check_l
        )
        c_n_s = "\n".join(
            "\n---- not match ---- [ {0} ] --- in file!\n".format(b.strip()) for b in check_not_match
        )
        log.info("=" * 80)
        log.info("we will modify file:%s " % path)
        log.info(c_s)
        if check_not_match:
            log.warning(c_n_s)

        log.info("=" * 80)

    return


def replace_file_by_key(key, ischeck=False):
    path = p_dict.get(key).get("path")
    conf = p_dict.get(key).get("conf")
    rex_replace(path, conf, ischeck)

def check_and_confirm():
    for k in p_dict.keys():
        replace_file_by_key(k, ischeck=True)
    

    if python_major < 3 :
        confirm = raw_input('continue ? (y/n)')
    else:
        confirm = input('continue ? (y/n)')
    if confirm == 'n':
        exit()
 
def replace_file():
    replace_file_by_key('gc_config_properies')
    replace_file_by_key('deploy_config_context_xml')


properties_rex = r'[^#]*[\s]*{0}=(.*?)\n'
properties_rex = r'[\s]*{0}[\s]*=[\s]*(.*?)\n'

def format_conf(p_dict):
    for k,p in p_dict.items():
        
        if p['file_type'] == 'properties':
            for c in p['conf']:
                c[0] = properties_rex.format(c[0])
        else:
            for c in p['conf']:
                pass


p_dict = {
    'home/portal/casServer/webapps/cas/WEB-INF/deployerConfigContext.xml':dict(  #1
        path = r'home/portal/casServer/webapps/cas/WEB-INF/deployerConfigContext.xml',
        conf = [
            ['<property name="url" value="jdbc:oracle:thin:@(.*?)"></property>', gc_db_url],
            ['<property name="username" value="(.*?)"></property>', portal_db_user],
            ['<property name="password" value="(.*?)"></property>', portal_db_passwd],
        ],
        file_type='xml',
    ),
    
    'home/portal/casServer/webapps/uic-api-web/WEB-INF/classes/jdbc.properties':dict(  #2
        path = r'home/portal/casServer/webapps/uic-api-web/WEB-INF/classes/jdbc.properties',
        conf = [
            ['jdbc.url', gc_db_url],
            ['jdbc.username', portal_db_user],
            ['jdbc.password', portal_db_passwd],
            ['zookeeper.address', '{0}:{1}'.format(zookeeper_host,zookeeper_port)],
        ],
        file_type='properties',
    ),
    
    'home/portal/casServer/webapps/uic-api-web/WEB-INF/classes/redis.properties':dict(  #3
        path = r'home/portal/casServer/webapps/uic-api-web/WEB-INF/classes/redis.properties',
        conf = [
            ['redis.host', redis_host],
            ['redis.port', redis_port],
        ],
        file_type='properties',
    ),
    
    'home/portal/casServer/webapps/uic-api-web/WEB-INF/classes/spring/uic-consumer.xml':dict(  #4
        path = r'home/portal/casServer/webapps/uic-api-web/WEB-INF/classes/spring/uic-consumer.xml',
        conf = [
            ['<dubbo:registry address="(.*?)" />', 'zookeeper://{0}:{1}'.format(zookeeper_host,zookeeper_port)],
        ],
        file_type='xml',
    ),
    
    'home/portal/portalServer/webapps/portal/WEB-INF/classes/config.properties':dict( #5
        path = r'home/portal/portalServer/webapps/portal/WEB-INF/classes/config.properties',
        conf = [
            ['ftpHostIp', portal_ftpHostIp],
            ['ftpPort', portal_ftpPort],
            ['userName', portal_ftp_userName],
            ['password', portal_ftp_password],
            ['casUrl', '{0}:{1}'.format(cas_host, cas_port)],
            ['omUrl', '{0}:{1}'.format(om_host, om_port)],
            ['wfmUrl', '{0}:{1}'.format(wfm_host, wfm_port)],
            ['amUrl', '{0}:{1}'.format(am_host, am_port)],
            ['weatherUrl', weatherUrl],
        ],
        file_type='properties',
    ),
    
    'home/portal/portalServer/webapps/portal/WEB-INF/classes/jdbc.properties':dict( #6
        path = r'home/portal/portalServer/webapps/portal/WEB-INF/classes/jdbc.properties',
        conf = [
            ['jdbc.url', gc_db_url],
            ['jdbc.username', portal_db_user],
            ['jdbc.password', portal_db_passwd],
            ['zookeeper.address', '{0}:{1}'.format(zookeeper_host,zookeeper_port)],
        ],
        file_type='properties',
    ),
    
    'home/portal/portalServer/webapps/portal/WEB-INF/classes/redis.properties':dict( #7
        path = r'home/portal/portalServer/webapps/portal/WEB-INF/classes/redis.properties',
        conf = [
            ['redis.host', redis_host],
            ['redis.port', redis_port],
        ],
        file_type='properties',
    ),
    
    'home/portal/portalServer/webapps/portal/WEB-INF/web.xml':dict(  #8
        path = r'home/portal/portalServer/webapps/portal/WEB-INF/web.xml',
        conf = [
            ['<param-value>http://(.*?)/cas/login</param-value>', '{0}:{1}'.format(cas_host,cas_port)],
            ['<param-name>serverName</param-name>[\s]*<param-value>http://(.*?)</param-value>', '{0}:{1}'.format(portal_host,portal_port)],
            ['<param-value>http://(.*?)/cas</param-value>', '{0}:{1}'.format(cas_host,cas_port)],
        ],
        file_type='xml',
    ),
    
    'home/bwp/bwp-service-4.0.0/usi-bwp-service-4.0.0-SNAPSHOT0518/dubbo.properties':dict(  #9
        path = r'home/bwp/bwp-service-4.0.0/usi-bwp-service-4.0.0-SNAPSHOT0518/dubbo.properties',
        conf = [
            ['dubbo.registry.address', 'zookeeper://{0}:{1}'.format(zookeeper_host,zookeeper_port)],
        ],
        file_type='properties',
    ),
    
    'home/bwp/bwp-service-4.0.0/usi-bwp-service-4.0.0-SNAPSHOT0518/starflow.properties':dict(  #10
        path = r'home/bwp/bwp-service-4.0.0/usi-bwp-service-4.0.0-SNAPSHOT0518/starflow.properties',
        conf = [
            ['jdbc.url', gc_db_url],
            ['jdbc.username', bwp_db_user],
            ['jdbc.password', bwp_db_passwd],
        ],
        file_type='properties',
    ),
    
    'home/bwp/bwp-web-4.0/apache-tomcat-7.0.59/webapps/bwp/WEB-INF/classes/META-INF/res/resource-development.properties':dict(  #11
        path = r'home/bwp/bwp-web-4.0/apache-tomcat-7.0.59/webapps/bwp/WEB-INF/classes/META-INF/res/resource-development.properties',
        conf = [
            ['jdbc.url', gc_db_url],
            ['jdbc.username', bwp_db_user],
            ['jdbc.password', bwp_db_passwd],
            ['zkAddress', '{0}:{1}'.format(zookeeper_host,2182)],
            ['restHost', 'http://{0}:{1}/bwp'.format(bwp_host,bwp_port)],
        ],
        file_type='properties',
    ),
    
    'home/om/omServer/webapps/om/WEB-INF/classes/config.properties':dict(  #12
        path = r'home/om/omServer/webapps/om/WEB-INF/classes/config.properties',
        conf = [
            ['ftpHostIp', om_ftpHostIp],
            ['ftpPort', om_ftpPort],
            ['userName', om_ftp_userName],
            ['password', om_ftp_password],
            ['bwp', '{0}:{1}'.format(bwp_host,bwp_port)],
            ['wms', '{0}:{1}'.format(wfm_host,wfm_port)],
            ['inas', '{0}:{1}'.format(am_host,am_port)],
        ],
        file_type='properties',
    ),
    
    'home/om/omServer/webapps/om/WEB-INF/classes/jdbc.properties':dict(   #13
        path = r'home/om/omServer/webapps/om/WEB-INF/classes/jdbc.properties',
        conf = [
            ['jdbc.url', gc_db_url],
            ['jdbc.username', om_db_user],
            ['jdbc.password', om_db_passwd],
            ['dubbo.zk.address', 'zookeeper://{0}:{1}'.format(zookeeper_host,zookeeper_port)],
            ['dubbo.bwp.zk', 'zookeeper://{0}:{1}'.format(zookeeper_host,zookeeper_port)],
        ],
        file_type='properties',
    ),
    
    'home/om/omServer/webapps/om/WEB-INF/classes/redis.properties':dict(  #14
        path = r'home/om/omServer/webapps/om/WEB-INF/classes/redis.properties',
        conf = [
            ['redis.host', redis_host],
            ['redis.port', redis_port],
        ],
        file_type='properties',
    ),
    
    'home/om/omServer/webapps/om/WEB-INF/web.xml':dict(  #15
        path = r'home/om/omServer/webapps/om/WEB-INF/web.xml',
        conf = [
            ['<param-value>http://(.*?)/cas/login</param-value>', '{0}:{1}'.format(cas_host,cas_port)],
            ['<param-name>serverName</param-name>[\s]*.*?[\s]*<param-value>http://(.*?)</param-value>',  '{0}:{1}'.format(om_host,om_port)],
        ],
        file_type='xml',
    ),
    
    'home/wfm/wfmServer/webapps/wfm/WEB-INF/classes/jdbc.properties':dict(  #16
        path = r'home/wfm/wfmServer/webapps/wfm/WEB-INF/classes/jdbc.properties',
        conf = [
            ['oracle.url', gc_db_url],
            ['oracle.username', om_db_user],
            ['oracle.password', om_db_passwd],
            ['oracle2.url', gc_db_url],
            ['oracle2.username', wfm_db_user2],
            ['oracle2.password', wfm_db_passwd2],
            ['bwp.address', 'zookeeper://{0}:{1}'.format(zookeeper_host,2182)],
            ['dubbo.address', 'zookeeper://{0}:{1}'.format(zookeeper_host,2181)],
        ],
        file_type='properties',
    ),
    
    'home/wfm/wfmServer/webapps/wfm/WEB-INF/classes/redis.properties':dict(  #17
        path = r'home/wfm/wfmServer/webapps/wfm/WEB-INF/classes/redis.properties',
        conf = [
            ['redis.host', redis_host],
            ['redis.port', redis_port],
        ],
        file_type='properties',
    ),
    
    'home/wfm/wfmServer/webapps/wfm/WEB-INF/web.xml':dict(   #18
        path = r'home/wfm/wfmServer/webapps/wfm/WEB-INF/web.xml',
        conf = [
            ['<param-value>http://(.*?)/cas/login</param-value>', '{0}:{1}'.format(cas_host,cas_port)],
            ['<param-value>http://(.*?)/cas/</param-value>', '{0}:{1}'.format(cas_host,cas_port)],
            ['<param-name>serverName</param-name>[\s]*.*?[\s]*.*?[\s]*<param-value>http://(.*?)</param-value>',  '{0}:{1}'.format(wfm_host,wfm_port)],
        ],
        file_type='xml',
    ),
    
    'home/am/apps/conf/mongodb.properties':dict(   #19
        path = r'home/am/apps/conf/mongodb.properties',
        conf = [
            ['mongo.host', mongodb_host],
            ['mongo.port', mongodb_port],
            ['mongo.defaultDbName', mongodb_defaultDbName],
            ['mongo.replicaSet', '{0}:{1}'.format(mongodb_host,mongodb_port)],
            ['mongo.user', mongodb_user],
            ['mongo.pwd', mongodb_passwd],
        ],
        file_type='properties',
    ),
    
    'home/am/apps/conf/redis.properties':dict(   #20
        path = r'home/am/apps/conf/redis.properties',
        conf = [
            ['redis.host', redis_host],
            ['redis.port', redis_port],
            ['redis.sentinel1.ip', redis_sentinel1_ip],
            ['redis.sentinel1.port', redis_sentinel1_port],
            ['redis.sentinel2.ip', redis_sentinel2_ip],
            ['redis.sentinel2.port', redis_sentinel2_port],
        ],
        file_type='properties',
    ),
    
    'home/am/apps/conf/jdbc.properties':dict(   #21
        path = r'home/am/apps/conf/jdbc.properties',
        conf = [
            ['jdbc.url', gc_db_url],
            ['jdbc.username', mongodb_port],
            ['jdbc.password', mongodb_defaultDbName],
            ['dubbo.zk.address', '{0}:{1}'.format(zookeeper_host,2181)],
        ],
        file_type='properties',
    ),
    
    'home/am/apps/conf/system-config.properties':dict(   #22
        path = r'home/am/apps/conf/system-config.properties',
        conf = [
            ['analyse.serverAddr', am_host],
            ['analyse.ruleRmiIp', am_host],
            ['analyse.ruleStaticdataRmiIp', am_host],
            ['analyse.rmiStaticdataUrl', 'rmi://{0}:7077'.format(am_host)],
            ['analyse.ruleDeployUrl', 'rmi://{0}:7077'.format(am_host)],
        ],
        file_type='properties',
    ),
    
    'home/am/web/tomcat/webapps/inas-web/WEB-INF/web.xml':dict(   #23
        path = r'home/am/web/tomcat/webapps/inas-web/WEB-INF/web.xml',
        conf = [
            ['<param-value>http://(.*?)/cas/login</param-value>', '{0}:{1}'.format(cas_host,cas_port)],
            ['<param-value>http://(.*?)/cas[/]*</param-value>', '{0}:{1}'.format(cas_host,cas_port)],
            ['<param-name>serverName</param-name>[\s]*.*?[\s]*<param-value>http://(.*?)</param-value>',  '{0}:{1}'.format(am_host,am_port)],
        ],
        file_type='xml',
    ),
    
    'home/am/tools/redis/conf/sentinel-16378.conf':dict(  #24
        path = r'home/am/tools/redis/conf/sentinel-16378.conf',
        conf = [
            ['sentinel monitor inasmaster(.*?)1', ' {0} {1} '.format(cas_host,cas_port)],
            ['\n[\s]*sentinel myid .*?\n', '\n'],
        ],
        file_type='xml',
    ),
}


if __name__ == '__main__':
    format_conf(p_dict)
    check_and_confirm()
    replace_file()
